package com.leps.nq.mobile;

import cn.hutool.core.bean.BeanUtil;
import com.leps.nq.common.util.FileUploadUtils;
import com.leps.nq.common.util.SecurityUtil;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.sys.entity.SysUser;
import com.leps.nq.sys.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Api(tags = "App端新增接口")
@RestController
public class MobileController {
    @Autowired
    ISysUserService userService;

    @ApiOperation("获取登录用户信息")
    @GetMapping("/user/profile")
    public R<SysUser> getUserProfile() {
        Long userId = SecurityUtil.getUserId();
        SysUser sysUser = userService.getById(userId);
        return RBuilder.ok(sysUser);
    }

    @ApiOperation("更新用户信息")
    @PutMapping("/user/profile")
    public R updateUserProfile(@RequestBody UserProfile profile) {
        SysUser user = BeanUtil.toBean(profile, SysUser.class);
        user.setUserId(SecurityUtil.getUserId());
        user.setUpdateBy(SecurityUtil.getUserName());
        boolean b = userService.updateById(user);
        return RBuilder.ofBoolean(b);
    }

    @ApiOperation("修改密码")
    @PutMapping("/user/pwd")
    public R changePwd(String oldPwd, String newPwd) {
        boolean b = this.userService.changePwdBySelf(oldPwd, newPwd);
        return RBuilder.ofBoolean(b);
    }

    @ApiOperation("上传头像")
    @PostMapping("/user/avatar")
    public R upAvatar(MultipartFile file) {
        String filename = FileUploadUtils.uploadAvatar(file);
        userService.lambdaUpdate().set(SysUser::getAvatar, filename).eq(SysUser::getUserId, SecurityUtil.getUserId()).update();
        return RBuilder.ok(filename);
    }
}
